import React from "react";
import PropTypes from 'prop-types';
import {connect} from "react-redux";
import {getFileList} from "../api/FileApi";
import FileItem from "../components/FileItem";
import store from "../redux/RuduxIndex";
import {Button, Row, Col} from "antd"
import "./Home.css"
import FilePathHelper from "../utils/FilePathHelper";

class Home extends React.Component {

    constructor(props, context) {
        super(props, context);
        this.props = {
            ...this.props,
            fileItems: {
                dirPath: ".",
                items: []
            },
        }
        this.state = {
            path: this.getCurrentQueryPath(),
        }
    }

    componentDidMount() {
        this.flesh();
    }

    flesh = () => {
        const {path} = this.getCurrentQueryPath();
        store.dispatch(getFileList(path));
    }

    getCurrentQueryPath = ()=> {
        const path = new URLSearchParams(this.props.location.search).get("path")??"."
        console.log("getCurrentQueryPath"+path)
        return path;
    }

    toUpperPage = () => {
        let path = this.getCurrentQueryPath();
        path = FilePathHelper.GetUpperPath(path)
        this.props.history.push({pathname: "/Home", search: new URLSearchParams({path: path}).toString()});
        store.dispatch(getFileList(path));
    }
    toDir = (path) => {
        this.props.history.push({pathname: "/Home", search: new URLSearchParams({path: path}).toString()});
        store.dispatch(getFileList(path));
    }

    render() {
        const {items, dirPath} = this.props.fileItems;
        const fileList = items?.map((val, index) =>
            <FileItem key={index} toDir={this.toDir} {...val}/>) ?? <span>no</span>;

        const topButton = (span, text, onClick) =>
            <Col span={span} className="top-buttons-item">
                <Button size="large" className="primary" onClick={onClick}>
                    {text}
                </Button>
            </Col>

        return <div>
            <Row className="top-buttons">
                <Col span={6}/>
                {topButton(4, "上一级", this.toUpperPage)}
                {topButton(4, "重置", () => this.toDir(""))}
                {topButton(4, "退出", this.logout)}
                <Col span={6}/>
            </Row>
            <div className="dir-path">
                <Row>
                    <Col span={6}/>
                    <Col span={18}>{dirPath === undefined || dirPath === null || dirPath === "" ? "." : dirPath}</Col>
                </Row>
            </div>
            <div>{fileList}</div>
        </div>
    }
}

export default Home = connect((state) => ({...state}))(Home);

Home.protoTypes = {
    fileItems: {
        dirPath: PropTypes.string.isRequired,
        items: PropTypes.array.isRequired
    },
}